<? if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Sales_model extends CI_Model
{
	public $num_edge_entries = 2;
	public $items_per_page = 10;

	public function save_sale_items($data)
	{
		$this->db->insert('sales_items', $data);
	}

	public function save_sale($data)
	{
		$this->db->insert('sales', $data);
	}

	public function get_sale_total_item_by_sale_id($id)
	{
		$this->db->select_sum('sale_item_total')->where('sale_id', $id);
		return $this->db->get('sales_items');
	}

	public function get_sales()
	{
		return $this->db->order_by('sale_created', 'desc')->get('sales');
	}

	public function get_sales_with_idx($idx)
	{
		$offset = $idx * $this->items_per_page;

		return $this->db
			->order_by('sale_created', 'desc')
			->get('sales', $this->items_per_page, $offset);
	}

	public function get_sale_total_item_by_item_id($id, $start=null,$end=null)
	{
		if($start)
		{
			$this->db->where('date(sales_item_created) >=', $start);
			$this->db->where('date(sales_item_created) <=', $end);
		}
		$this->db->select_sum('sale_item_total')->select_sum('sale_item_quantity')->select_sum('sale_item_discount_price')->where('item_id', $id);
		return $this->db->get('sales_items');
	}

	public function get_sale_item_by_sale_id($id)
	{
		$this->db->join('items', 'items.item_id = sales_items.item_id');
		$this->db->where('sales_items.sale_id', $id);
		return $this->db->get('sales_items');
	}
}